package com.leetcode.array.square.demo1;

/**
 * @Author Zan
 * @Create 2024/5/8 11:55
 * @ClassName: Test
 * @Description : https://leetcode.cn/problems/squares-of-a-sorted-array/  有序数组的平方
 */
public class Test {
    public static void main(String[] args) {

    }
}

// 暴力求解
class Solution {
    public int[] sortedSquares(int[] nums) {
        int size = nums.length;
        for (int i = 0; i < size; i++) {
            nums[i] = nums[i] * nums[i];
        }
        for (int i = 0; i < size; i++) {
            for (int j = i + 1; j < size; j++) {
                if (nums[i] > nums[j]) {
                    int temp = nums[i];
                    nums[i] = nums[j];
                    nums[j] = temp;
                }
            }
        }
        return nums;
    }
}

// 双指针
class Solution2 {
    public int[] sortedSquares(int[] nums) {
        int size = nums.length;
        int[] arr = new int[size];
        // 双指针的思路，创建新的数组，由于是有序的，左右两边平方比较，进行放置
        int left = 0;
        int right = size - 1;
        while (left <= right) {
            if (nums[left] * nums[left] <= nums[right] * nums[right]) {
                // 放右边的值
                arr[--size] = nums[right] * nums[right];
                right--;
            } else if (nums[left] * nums[left] > nums[right] * nums[right]) {
                arr[--size] = nums[left] * nums[left];
                left++;
            }
        }
        return arr;
    }
}
